package com.bing.bean.Tpp.stock.func;

import com.bing.bean.BingException;
import com.bing.bean.Tpp.stock.bean.Stock;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2015/5/31.
 */
public class StockUtil {
    private static final String GET_URL = "http://hq.sinajs.cn/list=";
    private static final Logger logger = LoggerFactory.getLogger(StockUtil.class);
    public static final int CODE_NOT_FOUND=1;
    public static final String MSG_NOT_FOUND="查询失败,股票代码不存在";

    public static List<Stock> gets(String[] codes) throws IOException {
        Assert.notEmpty(codes);
        List<Stock> stocks=new ArrayList<>();
        Document document = Jsoup.connect(GET_URL + StringUtils.arrayToCommaDelimitedString(codes)).ignoreContentType(true).get();
        Matcher matcher = Pattern.compile("hq_str_(?<daihao>.*?)=\"(?<detail>[^\"]*?)\";").matcher(document.text());
        while (matcher.find()) {
            String daihao = matcher.group("daihao");
            String detail = matcher.group("detail");
            logger.debug("查询股票:{},详情:{}", daihao, detail);
            if(!StringUtils.hasText(detail) || detail.equals("FAILED")){
                logger.error("查询为空.");
                throw new BingException(CODE_NOT_FOUND,MSG_NOT_FOUND);
            }
            stocks.add(Stock.fromString(daihao, detail));
        }
        return stocks;
    }

}
